package com.etlmaster.datax.plugins.writer.localfilewriter;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;

import com.dp.nebula.wormhole.common.AbstractPlugin;
import com.dp.nebula.wormhole.common.interfaces.ILine;
import com.dp.nebula.wormhole.common.interfaces.ILineReceiver;
import com.dp.nebula.wormhole.common.interfaces.IWriter;
import com.etlmaster.datax.plugins.writer.localwriter.ParamKey;
import com.etlmaster.executor.utils.LogWriter;

public class LocalFileWriter extends AbstractPlugin implements IWriter {

	private File file;
	private OutputStream out = null;
	private BufferedWriter bw = null;
	private String done_suffix = ".dat";
	private char fieldSplit;
	private char lineSplit;

	@Override
	public void init() {
		LogWriter.addLog("INFO","开始初始化");
		file = new File(getParam().getValue(ParamKey.fileName) + done_suffix);
		fieldSplit=getParam().getCharValue(ParamKey.fieldSplit); 
		lineSplit=getParam().getCharValue(ParamKey.lineSplit); 
		try {
			out = new FileOutputStream(file, false);
			bw = new BufferedWriter(new OutputStreamWriter(out, getParam()
					.getValue(ParamKey.encoding)));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	public void write(ILineReceiver lineReceiver) {
		ILine line;

		while ((line = lineReceiver.receive()) != null) {

			StringBuffer str = new StringBuffer();

			int len = line.getFieldNum();

			for (int i = 0; i < len; i++) {
				String ls = line.getField(i).toString();
				str.append(ls);
				str.append(fieldSplit);
			}
			str.deleteCharAt(str.length() - 1);
			str.append(lineSplit);
			writeLine(str.toString(), file);
		}
	}
	public void commit() {
		closeAll();

	}

	public void writeLine(String str, File file) {
		try {

			bw.write(str);
			bw.flush();
		} catch (FileNotFoundException e) {

			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {

			e.printStackTrace();
		} catch (IOException e) {

			e.printStackTrace();
		}
	}

	public void closeAll() {
		try {
			if (bw != null)
				bw.close();
			if (out != null)
				out.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
